Python's lambda Keyword as a Function

Here’s a quick one. In Python you can access the operators as a function when you import the operator module. For example, if you do from operator import *, every operator is imported in your namespace as a function, which means you can do things like add(2, 3) or is_(a, b).

However, not all keywords, like lambda, are not included. Well, that makes sense because how would you define the body of a function?! You would probably use another lambda expression, which makes the whole operation useless. But if you allow the body to be defined as a string and the arguments as a list of string, the following can be defined:

λ = lambda p, b: eval('lambda %s: %s' % (', '.join(p), b))

This “λ function” is a function which creates a python string (containing a new lambda expression), which is then interpreted as Python code.

It really works, even the “λ” character:

>>> λ(['x'], '2*x')(5)
10
>>> λ(['x', 'y'], 'x + y')('hello', 'world')
'helloworld'
>>> λ(['input'], 'print(input)')('test')
test

Finally, I can dynamically create lambda functions with list(str) parameters and a string body…


Update

There is a nice way to dynamically create classes. The type() function takes three parameters: a name, the base classes and a dict for the class body.

Which means that

class X:
    a = 1

is identical to

X = type('X', (object,), dict(a=1))

(taken from the Python3 docs).